package com.example.demo.demo.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: htc
 * @date: Created in 17:11 2018/3/23.
 */
public class MethodDemo1 {
    public static void main(String[] args) {
        /**
         * 要获取print(int, int)方法
         * 1.获取一个方法就是获取类的信息。首先要获取类的类类型
         */
        A a = new A();
        Class c = a.getClass();

        /**
         * 2.获取方法名称和参数列表来决定
         * getMethod()获取的是public的方法
         * getDeclaredMethod()获取自己声明的方法
         */
        try {
//        Method m = c.getMethod("print",new Class[]{int.class, int.class});
            Method m = c.getMethod("print", new Class[]{int.class, int.class});
            //方法的反射操作是用m对象来进行方法调用
//            Object o = m.invoke(a, new Object[]{10, 20});
            Object o = m.invoke(a, 10, 20);


            Method me = c.getMethod("print", new Class[]{String.class, String.class});
            Object ob = me.invoke(a, "10", "20");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

class A {
    public void print(int a, int b) {
        System.out.println(a + b);
    }

    public void print(String a, String b) {
        System.out.println(a.toUpperCase() + "," + b.toLowerCase());
    }
}
